define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "UtilDir/loading",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock, Loading) {

    var getFxPreestimateWorkspaceController = function () {
        return getServer() + "/fxPreestimateWorkspaces";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initTimeSelect();
        initMap();
    };
    var initTimeSelect = function () {
        $.ajax({
            url: getFxPreestimateWorkspaceController() + "/getValidDictItemsByDictCode/" + "year",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("timeSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            //createFxPreestimateWorkspaceGrid();
            queryWorkspaceByYear();
        });
        $("#btnReset").click(function () {
            $("#timeSelect").val("");
        });
        //批量上传
        $("#btnImport").click(function () {
            importForm();
        });
        $("#btnExport").click(function () {
            exportForm();
        });
    };

    /**
     * 导入
     */
    var importForm = function () {
        // 要上传的文件的后缀名数组
        var minList = [];
        // 要上传的文件的文件名数组
        var nameList = [];
        // var maxList = ["dbf","prj","shp","shx"];
        // 获取文件名
        $("#uploadFile").on("change", function () {
            var uploadinputFiles = document.getElementById("uploadFile").files;
            // debugger;
            minList = [];
            var text = "";
            for (var i = 0; i < uploadinputFiles.length; i++) {
                console.log("uploading: " + uploadinputFiles[i].name);
                text += uploadinputFiles[i].name + "\n";
                // 获取这个文件的后缀名
                minList.push(uploadinputFiles[i].name.slice(uploadinputFiles[i].name.length - 3, uploadinputFiles[i].name.length));
                nameList.push(uploadinputFiles[i].name.split(".")[0]);
            }
            $("#commentInfo").val(text);
        });
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/预评估工作区模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            for(var i = 0; i < uploadinput.files.length; i++){
                formData.append('files', uploadinput.files[i]);
            }
            // debugger;
            $.ajax({
                url: getFxPreestimateWorkspaceController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                }
            });
            $("#commentInfo").val("");
        });
    };

    /**
     * 导出
     */
    var exportForm = function () {
        var yearTime = $("#timeSelect").val();
        console.log("yearTime: ", yearTime);
        window.location.href = getFxPreestimateWorkspaceController() + "/export?time=" + yearTime;
    };


    /**
     * 导入
     */
        // var importSHPForm = function () {
        // 	// 模板下载
        // 	$("#uploadModal").modal();
        // 	$('#uploadButton').off("click");
        // 	$("#uploadButton").on("click", function () {
        // 		var uploadinput = document.getElementById("uploadFile");
        // 		if (uploadinput.value == "") {
        // 			Util.alert("上传前请先选择文件!");
        // 			return;
        // 		}
        // 		var formData = new FormData();
        // 		formData.append("file", uploadinput.files[0]);
        // 		console.log(formData, uploadinput.files[0]);
        // 		$.ajax({
        // 			url: getFxPreestimateWorkspaceController() + "/importSHP",
        // 			data: formData,
        // 			processData: false, //因为data值是FormData对象，不需要对数据做处理。
        // 			contentType: false,
        // 			type: "POST",
        // 			success: function (data) {
        // 				$('#uploadModal').modal('hide');
        // 				uploadinput.value = null;
        // 				Util.alert(data);
        // 			}
        // 		});
        // 	});
        // };

    var loading = Loading({text : "正在查询数据..."});
    var tdMap;
    var initMap = function () {
        var mapH = document.body.clientHeight - $(".pd-search-container").height() - 20;
        $("#fx-PEW-mapDiv").height(mapH);
        console.log("预评估工作区！")
        var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
        var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
        var config = {
            projection: 'EPSG:4326',
            minZoom: 4,
            layers: [vec_layer, cva_layer]
        };
        tdMap = new T.Map('fx-PEW-mapDiv', config), zoom = 4;
        tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);
    };

    var queryWorkspaceByYear = function () {
        tdMap.clearOverLays();
        var yearTime = $("#timeSelect").val();
        loading.show();
        $.ajax({
            url: getFxPreestimateWorkspaceController() + "/getFxPreestimateWorkspaces?time=" + yearTime,
            type: "GET",
            dataType: "json",
            success: function (data) {
                loading.close();
                //console.log(data);
                if (data && data.length) {
                    var total_points = [];
                    for (var idx = 0; idx < data.length; idx++) {
                        var coods_str = data[idx].coordinates;
                        var geometries = coods_str.split("|");
                        for (var k = 0; k < geometries.length; k++) {
                            var _coords = geometries[k].split(" "), points = [];
                            if (_coords.length == 1 && _coords[0] == "") continue;
                            for (var n = 0; n < _coords.length; n++) {
                                var coord = _coords[n].split(",");
                                var lon = parseFloat(coord[1]), lat = parseFloat(coord[0]);
                                points.push(new T.LngLat(lon, lat));
                            }
                            //console.log(points);
                            var polygon = new T.Polygon(points, {
                                color: "#0000ff",
                                weight: 1,
                                opacity: 0.5,
                                //fillColor: "#ffffff",
                                fillOpacity: 0.5
                            });
                            tdMap.addOverLay(polygon);
                            total_points = total_points.concat(points);
                        }
                    }
                    tdMap.setViewport(total_points);
                } else {
                    Util.alert("查询无数据!");
                }
            }
        });
    };

    return {
        init: init
    };
});